import { TYPES } from '../reducers/employeesReducer';
import Http from '../../../utils/http';
import _ from 'lodash';
import {
  Toast,
} from 'antd-mobile-rn';
import { i18n } from '../../../i18n/index';

export const getEmployeeList = () => async dispatch => {
  try {
    const http = new Http();

    dispatch({ type: TYPES.GET_EMPLOYEE_LIST });

    const { status, data } = await http.post('employeelist');

    if (status) {
      dispatch({ type: TYPES.GET_EMPLOYEE_LIST_SUCCESS, employees: data.rows });
    } else {
      throw new Exception();
    }
  } catch (_) {
    dispatch({ type: TYPES.GET_EMPLOYEE_LIST_FAIL });

    Toast.offline(i18n.t('employees.error.getemployelist'), 2);
  }
};

export const deleteEmployee = (userId) => async dispatch => {
  try {
    const http = new Http();

    dispatch({ type: TYPES.DELETE_EMPLOYEE });

    const { status, data } = await http.post('employeedelete', { user_id: userId });

    if (status) {
      dispatch({ type: TYPES.DELETE_EMPLOYEE_SUCCESS, user_id: userId });
    } else {
      throw new Exception();
    }
  } catch (_) {
    dispatch({ type: TYPES.DELETE_EMPLOYEED_FAIL });

    Toast.offline(i18n.t('employees.error.deleteemployee'), 1);
  }
};

export const addEmployee = () => {
  return {
    type: TYPES.ADD_EMPLOYEE,
  };
};

export const editEmployee = (employee) => {
  return {
    type: TYPES.EDIT_EXISTING_EMPLOYEE,
    employee,
  };
};

export const cancelEditEmployee = () => {
  return {
    type: TYPES.CANCEL_EDIT_EMPLOYEE,
  };
};

export const saveEmployee = (employee) => async dispatch => {
  try {
    const http = new Http();

    dispatch({ type: TYPES.SAVE_EMPLOYEE });

    let newEmployee = {
      ...employee,
    }
    let isAdded = true;
    if (newEmployee.user_id.length > 0) {
      isAdded = false;
    }

    const { status, data } = await http.post('employeesave', newEmployee);

    if (status) {
      if (isAdded) {
        const { user_id } = data;
        newEmployee.user_id = user_id;
      }

      dispatch({ type: TYPES.SAVE_EMPLOYEE_SUCCESS, employee: newEmployee, is_new: isAdded });
    } else {
      const { errors } = data;
      const firstError = errors[Object.keys(errors)[0]];

      dispatch({ type: TYPES.SAVE_EMPLOYEE_FAIL });

      Toast.offline(firstError, 2);
    }
  } catch (_) {
    dispatch({ type: TYPES.SAVE_EMPLOYEE_FAIL });

    Toast.offline(i18n.t('employees.error.saveemployee'), 2);
  }
};
